package lolxxs.chenyanting.controller;


import com.alibaba.fastjson.JSONObject;
import lolxxs.chenyanting.annotation.Cacheable;
import lolxxs.chenyanting.entity.Result;
import lolxxs.chenyanting.entity.StatusCode;
import lolxxs.chenyanting.model.User;
import lolxxs.chenyanting.service.IUserService;
import lolxxs.chenyanting.utils.HttpURLConnectionUtils;
import lolxxs.chenyanting.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 * @since 2021-12-30
 */
@RestController
@RequestMapping("/user")
@ConfigurationProperties("jwt.config") // 获取配置文件
public class UserController {

    private String key;
    private long ttl;
    private String appid;
    private String appsecret;
    //去掉无法注入

    public void setKey(String key) {
        this.key = key;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public void setAppsecret(String appsecret) {
        this.appsecret = appsecret;
    }

    @Autowired
    @Qualifier(value = "userServiceImpl")
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        int add = userService.add(user);
        if (add == 2) {
            return new Result(false, StatusCode.REGISTERERROR, "用户名已被注册");
        }
        if (add == 0) {
            return new Result(false, StatusCode.REGISTERERROR, "用户名或密码未填写");
        }
        if (add == 1) {
            return new Result(true, StatusCode.OK, "注册成功");
        }
        return new Result(false, StatusCode.REGISTERERROR, "注册失败");
    }

    @PostMapping("/login")
    @Cacheable(key = "key", value = "value")
    public Result login(@RequestBody User user) {
        System.out.println(user);
        user = userService.login(user);
        if (user == null) {
            return new Result(false, StatusCode.LOGINERROR, "登录失败");
        }
        String jwt = jwtUtil.createJWT(String.valueOf(user.getUserId()), user.getUserName(), user.getIdentity());
        //redisTemplate.opsForValue().set("login_"+jwt, 1, ttl, TimeUnit.MILLISECONDS);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("token", jwt);
        return  new Result(true, StatusCode.OK, "登录成功",map);
    }

    @PostMapping("/upload")
    public Result imageUpload(@RequestBody MultipartFile file) {
        String fileName = file.getOriginalFilename();   //原文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  //文件后缀
        String filePath = "D:/imgs/icons/";  //上传后的路径
        fileName = UUID.randomUUID() + suffixName;  //新文件名
        File dest = new File(filePath + fileName);  //文件全路径名
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("fileName",fileName);
        return new Result(true, StatusCode.OK, "上传成功",map);
    }


    @PostMapping("/remotelogin")
    public Result remoteLogin(@RequestBody String code) {

        Map<String, String> codemap = (Map) JSONObject.parseObject(code);
        if (codemap.get("code") == null) return null;
        String url = " https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appsecret+"&js_code="+codemap.get("code")+"&grant_type=authorization_code";
        String get = HttpURLConnectionUtils.doGet(url);

        Map<String, String> parse = (Map)JSONObject.parseObject(get);
//        System.out.println(parse);
        if (parse.get("openid") != null && parse.get("session_key") != null) {
            User user = new User();
            user.setOpenid(parse.get("openid"));
            List<User> query = userService.query(user);
            if (query == null || query.size() < 1) {
                User user1 = new User();
                user1.setOpenid(parse.get("openid"));
                user1.setUserName("");
                user1.setPassword("");
                userService.add(user1);
                String jwt = jwtUtil.createJWT(String.valueOf(user.getUserId()), "", user.getIdentity());
                redisTemplate.opsForValue().set("login_"+jwt, 1, ttl, TimeUnit.MILLISECONDS);
                Map<String, Object> map = new HashMap<>();
                map.put("user", user1);
                map.put("token", jwt);
                return new Result(true, StatusCode.OK, "登录成功",map);
            }
            else {
                String jwt = jwtUtil.createJWT(String.valueOf(user.getUserId()), "", user.getIdentity());
                redisTemplate.opsForValue().set("login_"+jwt, 1, ttl, TimeUnit.MILLISECONDS);
                Map<String, Object> map = new HashMap<>();
                map.put("user", query.get(0));
                map.put("token", jwt);
                return  new Result(true, StatusCode.OK, "登录成功",map);
            }
        }


        return  new Result(true, StatusCode.OK, "登录成功");
    }

    @PostMapping("/update")
    public Result update(HttpServletRequest request, @RequestBody User user) {
        Claims claims = (Claims)request.getAttribute("claims");
        if (claims != null) {
            if (claims.getId() != null) {
                if ((Integer)claims.get("identity") <  1) {// 如果非HR访问只能访问自己的数据
                    user.setUserId(Long.valueOf(claims.getId()));
                }
                user.setUserId(Long.valueOf(claims.getId()));
                boolean update = userService.update(user);
                if (update) {
                    return new Result(false, StatusCode.OK, "修改成功");
                }
            }
        }
        return new Result(true, StatusCode.UPDATEERROR, "修改失败");
    }

    @PostMapping("/query")
    public Result query(HttpServletRequest request, @RequestBody User user) {
        Claims claims = (Claims)request.getAttribute("claims");
        if (claims != null) { //&& (Integer)claims.get("identity") >=  1 限制只能HR访问
            if (claims.getId() != null ) {
                if ((Integer)claims.get("identity") <  1) {// 如果非HR访问只能访问自己的数据
                    user.setUserId(Long.valueOf(claims.getId()));
                }
                List<User> query = userService.query(user);
                if (query != null && query.size() > 0) {
                    return new Result(true, StatusCode.OK, "查询成功",query);
                } else {
                    return new Result(true, StatusCode.NOTFOUND, "没有找到记录");
                }
            }
        }
        return new Result(false, StatusCode.ACCESSERROR, "没有权限");
    }

    @PostMapping("/delete")
    public Result delete(HttpServletRequest request, @RequestBody User user) {
        Claims claims = (Claims)request.getAttribute("claims");
        if (claims != null) {//删除用户只能HR以上的级别做
            if (claims.getId() != null && (Integer)claims.get("identity") >=  1) {
                int row = userService.delete(user);
                if (row > 0) {
                    return new Result(true, StatusCode.OK, "删除成功", row);
                } else {
                    return new Result(true, StatusCode.NOTFOUND, "没有找到记录");
                }
            }
        }
        return new Result(false, StatusCode.ACCESSERROR, "没有权限");
    }
}
